package com.gongj.shej.代理模式;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @program: shej
 * @description: JDK动态代理
 * @author: gongj
 * @Description: TODO
 * @create: 2020-07-23 13:58
 **/
public class DynamicProxyHandler implements InvocationHandler {
    private Object target;

    public DynamicProxyHandler(Object target) {
        this.target = target;
    }

    public DynamicProxyHandler() {
    }

    public Object newProxyInstance(Object target) {
        this.target = target;
        Object result = Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), this);
        return result;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        this.before();
        Object invoke = method.invoke(target, args);
        this.after();
        return invoke;
    }

    private void before() {
        System.out.println("婚庆公司布置结婚现场===");
    }

    /**
     * 后处理
     */
    private void after() {
        System.out.println("婚庆公司打扫结婚现场===");
    }

    public static void main(String[] args) {
        Marry2 marry2 = new Me2();
        System.out.println(marry2.getClass());
        //Marry2 me2Proxy = (Marry2) Proxy.newProxyInstance(Marry2.class.getClassLoader(), Marry2.class.getInterfaces(), new DynamicProxyHandler(marry2));
        DynamicProxyHandler dynamicProxyHandler = new DynamicProxyHandler();
        Marry2 me2Proxy = (Marry2) dynamicProxyHandler.newProxyInstance(marry2);
        System.out.println(me2Proxy.getClass());
        me2Proxy.happrMarry();
    }
}


//结婚
interface Marry2 {
    void happrMarry();
}

//我
class Me2 implements Marry2{

    @Override
    public void happrMarry() {
        System.out.println("我要结婚啦，好开心阿");
    }
}